<template>
  <div class="app-container">
    <Header title="购物车案例"></Header>
    <!-- 循环渲染每个商品信息 -->
    <!-- 商品区域 -->
    <Goods v-for="item in goodsList" :id="item.id" :key="item.id" :name="item.goods_name" :img="item.goods_img" :price="item.goods_price" :state="item.goods_state" :count="item.goods_count" @state-change="getNewState"  ></Goods>
      <!-- Footer区域 -->
    <Footer :fullState="fullState" :sum="sumPrice" @all-checked="allChecked" ></Footer>
  </div>
</template>

<script>
import Footer from '@/components/Footer/Footer.vue';
import Goods from '@/components/Goods/Goods.vue';
import Header from '@/components/Header/Header.vue';
import axios from 'axios';
import bus from '@/components/eventBus.js'


export default {
  data(){
    return{
      goodsList:[],
    }
  },
  computed:{
    fullState(){
      return this.goodsList.every(item=> item.goods_state)
    },
    sumPrice(){
      return this.goodsList.filter(item=>item.goods_state).reduce((total,item)=>(
        total += item.goods_price*item.goods_count
      ),0);
    }
  },
  components:{
    Header,
    Goods,
    Footer
  },
  methods:{
    async initCartList(){
      let {data:res} = await axios.get('https://www.escook.cn/api/cart');
      console.log(res);
      if(res.status === 200){
        this.goodsList = res.list;
      }
    },
    getNewState(e){
      // 接收到子组件传入的值
      this.goodsList.some(item=>{
        if(e.id === item.id){
          item.goods_state = !item.goods_state;
          return true;
        }
      })
    },
    allChecked(e){
      this.goodsList.forEach(item=>{
        item.goods_state = e.state; 
      })
    },
    
  },
  created(){
    this.initCartList();
    bus.$on('share', val => {
      this.goodsList.some(item => {
        if (item.id === val.id) {
          item.goods_count = val.value
          return true
        }
      })
    });
  },
  mounted(){
    
  }
}
</script>

<style lang="less" scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
